/*
 * @(#)FtpUtil.java Apr 9, 2008
 * 
 * Copyright 2007 by ChinanetCenter Corporation.
 *
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * ChinanetCenter Corporation ("Confidential Information").  You
 * shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement
 * you entered into with ChinanetCenter.
 * 
 */
package com.cnc.fd.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.cnc.bas.util.Log;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;

import sun.net.TelnetInputStream;
import sun.net.ftp.FtpClient;

/**
 * @author 阿闲
 * @date   Apr 9, 2008
 * @version 1.0
 */
public class FtpUtil {
	
	private static Log log = Log.getLogger(FtpUtil.class);

	/**
	 * 获取用户根目录下的所有目录，并封装成页面下拉标签可以使用的数据结构
	 * @param serverIP
	 * @param usr
	 * @param pwd
	 * @return
	 */
	public static List<Map> getRootDirs(String serverIP, String usr, String pwd){
		
		List<Map> list = new ArrayList<Map>();
			
		FtpClient ftpClient = null;
			
			try{
					ftpClient = new FtpClient();	
					ftpClient.openServer(serverIP);
					ftpClient.setConnectTimeout(5*1000);
					ftpClient.setReadTimeout(5*1000);
        	        
					ftpClient.login(usr,pwd);
        	        
        	        TelnetInputStream tis = ftpClient.list();
        	        
        	        BufferedReader br = new BufferedReader(new InputStreamReader(tis));
        	      
        	        String line = null;
        	        
        	        while ((line = br.readLine()) != null){	          	        	
        	        
        	        	if(line.startsWith("d")){        	        		
        	        		log.logDebug(line);
        	        		String[] rows = line.split("\\s");
        	        		String dir = rows[rows.length -1];
        	        		Map record = new HashMap();
        	        		record.put("label", dir);
        	        		record.put("value", dir);
        	        		list.add(record);
        	        	}
        	        } 
        	       
	        
			}catch(Exception e){
				
				log.logError(e);
				
			}	finally{
				
				if(ftpClient != null){
					try {
						ftpClient.closeServer();
					} catch (IOException e) {
						//do nothing
					}
				}
					
			}
		
		return list;
	}
	
	/**
	 * 测试ftp用户是否创建
	 * @param hostIp
	 * @param ftpUser
	 * @param ftpPwd
	 * @return
	 */
	public static String testFtpUser(String hostIp, String ftpUser, String ftpPwd){
		
		StringBuffer msg = new StringBuffer();
		
		FtpClient ftpClient = null;
		
		try {
			
			ftpClient = new FtpClient(hostIp);
			
			ftpClient.login(ftpUser, ftpPwd);			
			
			msg.append(ftpUser).append(" has created on ").append(hostIp);
			log.logInfo(msg);
			
		} catch (IOException e) {
			msg.append("test ftp failure, host is ").append(hostIp)
			.append(", ftpUser is ").append(ftpUser)
			.append(". ").append(e.getMessage());
			log.logError(msg, e);
		}finally{
			if(ftpClient != null){
				try {
					ftpClient.closeServer();
				} catch (IOException e) {
					//do nothing
				}
			}
		}
		
		return msg.toString();
	}
	
	/**
	 * 批量创建ftp用户
	 * @param hostIp
	 * @param sshUsr
	 * @param sshPwd
	 * @param sshPort
	 * @param users
	 * @return
	 */
	public static String createAllFtpUser(String hostIp, String sshUsr, String sshPwd, int sshPort, String[] users){
		
		StringBuffer command = new StringBuffer();
		
		for(int i=0; i< users.length; i++){
			command.append("/usr/local/fileDistribute2/bin/makeUser.sh ").append(users[i]).append(";");
		}
		StringBuffer msg = new StringBuffer();		
		
		
		Connection conn = null;
		
		Session session = null;	
		
		try {
			conn = new Connection(hostIp, sshPort);
			
			conn.connect(null, 5*1000, 5*1000);
		
			boolean isAuth = conn.authenticateWithPassword(sshUsr, sshPwd);
			
			if(!isAuth){				
				msg.append("authenticate failure, hostIp ").append(hostIp);
				log.logError(msg);
				return msg.toString();
			}
			
			session = conn.openSession();				
	
			session.execCommand(command.toString());
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(
		    		session.getStdout()));
		    String line;
		    while((line = reader.readLine())!= null){		    	
		    	log.logInfo(line);
		    }
		    
		   reader.close();
		   
		   if(session.getExitStatus().intValue() ==0){
			   msg.append("create ftp user success, hostIp ").append(hostIp);
			   log.logInfo(msg);
			   return msg.toString();
		   }else{
			   msg.append("create ftp user failure. exit code is ")
			   .append(session.getExitStatus().intValue())
			   .append(" , hostIp ").append(hostIp);
			   log.logError(msg);
			   return msg.toString();
		   }		   
			
		} catch (IOException e) {
			
			msg.append("create ftp user failure because ").append(e.getMessage());
			log.logError(msg, e);
			return msg.toString();
			
		}finally{
			
			if(session != null)
				session.close();
			
			if(conn != null)
				conn.close();			
		}	
	}
	
	/**
	 * 通过ssh远程创建ftp用户
	 * @param hostIp
	 * @param sshUsr
	 * @param sshPwd
	 * @param sshPort
	 * @param ftpUser
	 * @return
	 */
	public static String createFtpUser(String hostIp, String sshUsr, String sshPwd, int sshPort, String ftpUser){
		
		return FtpUtil.createAllFtpUser(hostIp, sshUsr, sshPwd, sshPort, new String[]{ftpUser});
		
	}
	
	/**
	 * 通过ftp查询客户文件是否存在
	 * @param hostIp
	 * @param ftpUsr
	 * @param ftpPwd
	 * @param ftpPort
	 * @param ftpUser
	 * @param file
	 * @return
	 */
	public static boolean isFileExist(String hostIp, String ftpUser, String ftpPwd, String file)
	{
        FtpClient ftpClient = null;
		StringBuffer msg=new StringBuffer();
		String filePath;
		String filename;
		boolean isExist=false;
		List<String> fileList=new ArrayList<String>();
		try {
			
			ftpClient = new FtpClient(hostIp);	
			ftpClient.login(ftpUser, ftpPwd);			
//
//			if (-1 != file.indexOf("/")) {
//				filePath = file.substring(0, file.lastIndexOf("/"));
//				filename=file.substring(file.lastIndexOf("/")+1);
//			} else {
//				filePath = "/";
//				filename=file;
//			}
			TelnetInputStream tis=ftpClient.nameList(file);
			byte[] bytes=new byte[100];
			int ret=tis.read(bytes);
			if(-1!=ret)
			{
				String aux=new String(bytes).trim();
				//System.out.println(aux);
//				System.out.println("File:  "+file+" exist.");
				tis.close();
				return true;
			}else{
//				System.out.println("File:  "+file+" doesn't exist.");
				tis.close();
				return false;
			}

		} catch (IOException e) {
			msg.append("FtpUtil: ftp connection failed, host is ").append(hostIp)
			.append(", ftpUser is ").append(ftpUser)
			.append(". ").append(e.getMessage());
			log.logError(msg, e);
			return false;
		}finally{
			if(ftpClient != null){
				try {
					ftpClient.closeServer();
					fileList.clear();
				} catch (IOException e) {
					//do nothing
				}
			}
		}
	}
	
	public static boolean isFileExistBySSH(String hostIp, String sshUsr, String sshPwd, int sshPort, String file)
	{
		StringBuffer command = new StringBuffer();
		String filePath;
		String filename;
		if (-1 != file.indexOf("/")) {
			filePath = file.substring(0, file.lastIndexOf("/"));
			filename=file.substring(file.lastIndexOf("/")+1);
		} else {
			filePath = "/";
			filename=file;
		}
		command.append("cd ").append(filePath).append(";/usr/local/fileDistribute/bin/isFileExist.sh ").append(filename).append(";");
		
		StringBuffer msg = new StringBuffer();		
		
		Connection conn = null;		
		Session session = null;	
		
		try {
			conn = new Connection(hostIp, sshPort);
			
			conn.connect(null, 5*1000, 5*1000);
		
			boolean isAuth = conn.authenticateWithPassword(sshUsr, sshPwd);
			
			if(!isAuth){				
				msg.append("authenticate failure, hostIp ").append(hostIp);
				log.logError(msg);
				return false;
			}
			
			session = conn.openSession();				
	
			session.execCommand(command.toString());
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(
		    		session.getStdout()));
		    String line;
		    while((line = reader.readLine())!= null){		    	
		    	log.logInfo(line);
		    }
		    
		   reader.close();
		   
		   if(0==session.getExitStatus().intValue()){
			   msg.append("FtpUtil:  file ").append(file).append(" exist.");
			//   log.logInfo(msg);
			   return true;
		   }else{
			   msg.append("FtpUtil:  file ").append(file).append(" does't exist. \nret ")
			   .append(session.getExitStatus().intValue());
			//   log.logError(msg);
			   return false;
		   }		   
			
		} catch (IOException e) {
			
			msg.append("Exception is triggered, because ").append(e.getMessage());
			log.logError(msg, e);
			return false;
			
		}finally{
			
			if(session != null)
				session.close();
			
			if(conn != null)
				conn.close();			
		}	
	}
	
	public static void main(String[] args){
//		FtpUtil.testFtpUser("192.168.19.69", "55", "55");
//		FtpUtil.isFileExistBySSH("192.168.31.135","root", "12345678",22,"/home/ftpsite/test/cacheAppMas.sql");
//		System.out.println(FtpUtil.isFileExist("121.14.249.132","test", "1234","openSource/haproxy-1.3.15.11.tar.gz"));
		System.out.println(FtpUtil.getRootDirs("192.168.19.6", "test","123" ));
	}
	
	
}


